package com.mask.im.business.strategy.impl.recoveraccount;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mask.im.business.model.entity.UserAuth;
import com.mask.im.business.common.exception.BusinessException;
import com.mask.im.business.mapper.UserAuthMapper;
import com.mask.im.business.model.vo.IdentityVerificationVO;
import com.mask.im.business.service.RedisService;
import com.mask.im.business.strategy.RecoverAccountStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.mask.im.business.common.constant.RedisConstant.EMAIL_ACCOUNT_RECOVERY;

@Service("emailAccountRecoveryImpl")
public class EmailAccountRecoveryImpl implements RecoverAccountStrategy {

	@Autowired
	private RedisService redisService;

	@Autowired
	private UserAuthMapper userAuthMapper;

	@Override
	public List<String> findAccount(IdentityVerificationVO verificationVO) {
		check(verificationVO);
		List<UserAuth> userAuths = userAuthMapper.selectList(new LambdaQueryWrapper<UserAuth>()
				.eq(UserAuth::getEmail, verificationVO.getEmail())
				.orderByDesc(UserAuth::getLoginType));
		redisService.del(EMAIL_ACCOUNT_RECOVERY+ verificationVO.getEmail());
		if (!CollectionUtils.isEmpty(userAuths)){
			return userAuths.stream().filter(item -> Objects
					.nonNull(item.getUsername()))
					.map(UserAuth::getUsername)
					.collect(Collectors.toList());
		}
		return new ArrayList<>();
	}

	public void check(IdentityVerificationVO verificationVO) {
		if (!Validator.isEmail(verificationVO.getEmail())) {
			throw new BusinessException("邮箱格式不正确");
		}
		Object code = redisService.get(EMAIL_ACCOUNT_RECOVERY + verificationVO.getEmail());
		if (Objects.isNull(code)) {
			throw new BusinessException("验证码已过期，请重新获取");
		}
		if (!verificationVO.getCode().equals(code.toString())) {
			throw new BusinessException("验证码不正确，请重新输入");
		}
	}
}
